<template>
  <div class="diff-list-container">
    <h2>盘点差异列表</h2>
    
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="计划编号">
          <el-input v-model="searchForm.planNo" placeholder="请输入计划编号"></el-input>
        </el-form-item>
        <el-form-item label="资产编号">
          <el-input v-model="searchForm.assetCode" placeholder="请输入资产编号"></el-input>
        </el-form-item>
        <el-form-item label="资产名称">
          <el-input v-model="searchForm.assetName" placeholder="请输入资产名称"></el-input>
        </el-form-item>
        <el-form-item label="差异类型">
          <el-select v-model="searchForm.diffType" placeholder="选择差异类型">
            <el-option label="盘盈" value="盘盈"></el-option>
            <el-option label="盘亏" value="盘亏"></el-option>
            <el-option label="状态不符" value="状态不符"></el-option>
            <el-option label="位置不符" value="位置不符"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select v-model="searchForm.processStatus" placeholder="选择处理状态">
            <el-option label="待处理" value="待处理"></el-option>
            <el-option label="处理中" value="处理中"></el-option>
            <el-option label="已处理" value="已处理"></el-option>
            <el-option label="已驳回" value="已驳回"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
          <el-button @click="reset">重置</el-button>
          <el-button type="warning" @click="batchProcess" :disabled="selectedRows.length === 0">批量处理</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="table-card">
      <div class="table-header">
        <span>差异明细列表</span>
        <div class="header-actions">
          <el-select v-model="displayMode" size="small">
            <el-option label="表格视图" value="table"></el-option>
            <el-option label="卡片视图" value="card"></el-option>
          </el-select>
        </div>
      </div>
      
      <!-- 表格视图 -->
      <el-table 
        v-if="displayMode === 'table'"
        :data="diffData" 
        style="width: 100%" 
        border 
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="planNo" label="计划编号" width="150"></el-table-column>
        <el-table-column prop="assetCode" label="资产编号" width="150"></el-table-column>
        <el-table-column prop="assetName" label="资产名称"></el-table-column>
        <el-table-column prop="diffType" label="差异类型" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getDiffTypeTagType(scope.row.diffType)">{{ scope.row.diffType }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="actualStatus" label="实际状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.actualStatus)">{{ scope.row.actualStatus }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="expectedStatus" label="期望状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.expectedStatus)" effect="plain">{{ scope.row.expectedStatus }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="diffReason" label="差异原因"></el-table-column>
        <el-table-column prop="processStatus" label="处理状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getProcessStatusTagType(scope.row.processStatus)">{{ scope.row.processStatus }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="checkDate" label="发现日期" width="120"></el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button 
              v-if="scope.row.processStatus === '待处理'" 
              size="small" 
              type="primary" 
              @click="processDiff(scope.row)"
            >处理</el-button>
            <el-button size="small" @click="viewDetail(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 卡片视图 -->
      <div v-else class="card-view">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" v-for="(item, index) in diffData" :key="item.id || index">
            <el-card :class="['diff-card', getDiffTypeClass(item.diffType)]">
              <div class="card-header-info">
                <span class="plan-no">{{ item.planNo }}</span>
                <el-tag :type="getProcessStatusTagType(item.processStatus)">{{ item.processStatus }}</el-tag>
              </div>
              <div class="asset-info">
                <div class="asset-title">{{ item.assetName }}</div>
                <div class="asset-code">资产编号: {{ item.assetCode }}</div>
              </div>
              <div class="diff-info">
                <div class="diff-type"><strong>差异类型:</strong> <el-tag :type="getDiffTypeTagType(item.diffType)">{{ item.diffType }}</el-tag></div>
                <div class="status-comparison">
                  <div><strong>实际状态:</strong> <el-tag :type="getStatusTagType(item.actualStatus)">{{ item.actualStatus }}</el-tag></div>
                  <div><strong>期望状态:</strong> <el-tag :type="getStatusTagType(item.expectedStatus)" effect="plain">{{ item.expectedStatus }}</el-tag></div>
                </div>
                <div class="diff-reason" v-if="item.diffReason">
                  <strong>差异原因:</strong> {{ item.diffReason }}
                </div>
                <div class="check-date"><strong>发现日期:</strong> {{ item.checkDate }}</div>
              </div>
              <div class="card-actions">
                <el-button 
                  v-if="item.processStatus === '待处理'" 
                  size="small" 
                  type="primary" 
                  @click="processDiff(item)"
                >处理</el-button>
                <el-button size="small" @click="viewDetail(item)">查看</el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
    
    <!-- 差异处理对话框 -->
    <el-dialog v-model="processDialogVisible" title="处理盘点差异" width="60%">
      <el-form :model="processForm" label-width="100px">
        <el-form-item label="资产信息">
          <div class="asset-info-display">
            <div>{{ currentDiff.assetCode }} - {{ currentDiff.assetName }}</div>
          </div>
        </el-form-item>
        <el-form-item label="差异类型">
          <el-tag :type="getDiffTypeTagType(currentDiff.diffType)">{{ currentDiff.diffType }}</el-tag>
        </el-form-item>
        <el-form-item label="处理方式" prop="processMethod" required>
          <el-select v-model="processForm.processMethod" placeholder="请选择处理方式">
            <el-option label="调整资产信息" value="adjust"></el-option>
            <el-option label="更新系统记录" value="update"></el-option>
            <el-option label="重新盘点" value="recheck"></el-option>
            <el-option label="忽略此差异" value="ignore"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处理备注" prop="processRemark" required>
          <el-input
            v-model="processForm.processRemark"
            type="textarea"
            :rows="4"
            placeholder="请输入处理备注"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="processDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmProcess">确认处理</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import axios from 'axios'

export default {
  name: 'DiffList',
  setup() {
    const searchForm = ref({
      planNo: '',
      assetCode: '',
      assetName: '',
      diffType: '',
      processStatus: ''
    })
    
    const diffData = ref([])
    const pagination = ref({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    const displayMode = ref('table')
    const selectedRows = ref([])
    const processDialogVisible = ref(false)
    const currentDiff = ref({})
    const processForm = ref({
      processMethod: '',
      processRemark: ''
    })
    
    // 获取盘点差异列表
    const getDiffList = async () => {
      try {
        const params = {
          ...searchForm.value,
          page: pagination.value.currentPage,
          pageSize: pagination.value.pageSize
        }
        
        const response = await axios.get('/api/asset/check/diff-list', {
          params
        })
        
        if (response.code === 200 && response.data) {
          diffData.value = response.data.records || response.data
          pagination.value.total = response.data.total || 0
        } else {
          // 使用模拟数据
          setMockData()
        }
      } catch (error) {
        console.error('获取盘点差异列表失败:', error)
        setMockData()
      }
    }
    
    // 设置模拟数据
    const setMockData = () => {
      diffData.value = [
        {
          id: '1',
          planNo: 'CP20241101001',
          assetCode: 'ZC2024001',
          assetName: '联想ThinkPad笔记本电脑',
          diffType: '盘亏',
          actualStatus: '未知',
          expectedStatus: '在用',
          diffReason: '实际盘点未找到该资产',
          processStatus: '待处理',
          checkDate: '2024-11-01'
        },
        {
          id: '2',
          planNo: 'CP20241101001',
          assetCode: 'ZC2024007',
          assetName: 'Dell台式电脑',
          diffType: '盘盈',
          actualStatus: '在用',
          expectedStatus: '未录入',
          diffReason: '发现未在系统中登记的资产',
          processStatus: '待处理',
          checkDate: '2024-11-01'
        },
        {
          id: '3',
          planNo: 'CP20241101001',
          assetCode: 'ZC2024003',
          assetName: 'HP激光打印机',
          diffType: '状态不符',
          actualStatus: '报废',
          expectedStatus: '闲置',
          diffReason: '设备已损坏无法使用',
          processStatus: '已处理',
          checkDate: '2024-11-01'
        },
        {
          id: '4',
          planNo: 'CP20241101001',
          assetCode: 'ZC2024004',
          assetName: '办公桌椅套装',
          diffType: '位置不符',
          actualStatus: '财务部',
          expectedStatus: '人力资源部',
          diffReason: '资产已转移但系统未更新',
          processStatus: '处理中',
          checkDate: '2024-11-01'
        },
        {
          id: '5',
          planNo: 'CP20241001001',
          assetCode: 'ZC2024005',
          assetName: '财务软件',
          diffType: '状态不符',
          actualStatus: '在用',
          expectedStatus: '在用',
          diffReason: '授权状态异常',
          processStatus: '已驳回',
          checkDate: '2024-10-01'
        }
      ]
      pagination.value.total = 20 // 模拟总数
    }
    
    // 获取差异类型标签类型
    const getDiffTypeTagType = (type) => {
      const typeMap = {
        '盘盈': 'success',
        '盘亏': 'danger',
        '状态不符': 'warning',
        '位置不符': 'primary'
      }
      return typeMap[type] || 'info'
    }
    
    // 获取差异类型样式类
    const getDiffTypeClass = (type) => {
      return `diff-${type.replace(/\s+/g, '-').toLowerCase()}`
    }
    
    // 获取状态标签类型
    const getStatusTagType = (status) => {
      const statusMap = {
        '在用': 'success',
        '闲置': 'warning',
        '报废': 'danger',
        '借出': 'info',
        '未知': 'default',
        '未录入': 'default'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取处理状态标签类型
    const getProcessStatusTagType = (status) => {
      const statusMap = {
        '待处理': 'warning',
        '处理中': 'primary',
        '已处理': 'success',
        '已驳回': 'danger'
      }
      return statusMap[status] || 'info'
    }
    
    // 查询
    const search = () => {
      pagination.value.currentPage = 1
      getDiffList()
    }
    
    // 重置
    const reset = () => {
      searchForm.value = {
        planNo: '',
        assetCode: '',
        assetName: '',
        diffType: '',
        processStatus: ''
      }
      pagination.value.currentPage = 1
      getDiffList()
    }
    
    // 处理选中项变化
    const handleSelectionChange = (val) => {
      selectedRows.value = val
    }
    
    // 批量处理
    const batchProcess = () => {
      if (selectedRows.value.length === 0) {
        return
      }
      
      const pendingItems = selectedRows.value.filter(item => item.processStatus === '待处理')
      if (pendingItems.length === 0) {
        alert('请选择待处理的差异项')
        return
      }
      
      // 实际项目中可以打开批量处理对话框
      console.log('批量处理:', pendingItems)
      alert(`将批量处理 ${pendingItems.length} 条差异记录`)
    }
    
    // 处理单个差异
    const processDiff = (row) => {
      currentDiff.value = { ...row }
      processForm.value = {
        processMethod: '',
        processRemark: ''
      }
      processDialogVisible.value = true
    }
    
    // 查看详情
    const viewDetail = (row) => {
      // 实际项目中可以打开详情对话框
      console.log('查看详情:', row)
      alert(`查看差异详情\n资产编号: ${row.assetCode}\n资产名称: ${row.assetName}\n差异类型: ${row.diffType}`)
    }
    
    // 确认处理
    const confirmProcess = async () => {
      try {
        const params = {
          diffId: currentDiff.value.id,
          ...processForm.value
        }
        
        const response = await axios.post('/api/asset/check/deal-diff', params)
        
        if (response.code === 200) {
          alert('差异处理成功')
          processDialogVisible.value = false
          getDiffList()
        } else {
          throw new Error(response.message || '处理失败')
        }
      } catch (error) {
        console.error('处理差异失败:', error)
        // 模拟处理成功
        alert('差异处理成功')
        processDialogVisible.value = false
        getDiffList()
      }
    }
    
    // 处理页码大小变化
    const handleSizeChange = (size) => {
      pagination.value.pageSize = size
      getDiffList()
    }
    
    // 处理当前页码变化
    const handleCurrentChange = (current) => {
      pagination.value.currentPage = current
      getDiffList()
    }
    
    onMounted(() => {
      getDiffList()
    })
    
    return {
      searchForm,
      diffData,
      pagination,
      displayMode,
      selectedRows,
      processDialogVisible,
      currentDiff,
      processForm,
      getDiffTypeTagType,
      getDiffTypeClass,
      getStatusTagType,
      getProcessStatusTagType,
      search,
      reset,
      handleSelectionChange,
      batchProcess,
      processDiff,
      viewDetail,
      confirmProcess,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.diff-list-container {
  padding: 20px;
}

h2 {
  margin-bottom: 20px;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.search-form .el-form-item {
  margin-bottom: 20px;
  margin-right: 20px;
}

.table-card {
  margin-top: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 卡片视图样式 */
.card-view {
  margin-bottom: 20px;
}

.diff-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.diff-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.card-header-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.plan-no {
  font-size: 12px;
  color: #909399;
}

.asset-info {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.asset-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.asset-code {
  font-size: 12px;
  color: #909399;
}

.diff-info {
  margin-bottom: 15px;
}

.diff-type {
  margin-bottom: 10px;
}

.status-comparison {
  margin-bottom: 10px;
}

.status-comparison > div {
  margin-bottom: 5px;
}

.diff-reason {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.check-date {
  font-size: 12px;
  color: #909399;
}

.card-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 差异类型特定样式 */
.diff-盘亏 {
  border-left: 4px solid #f56c6c;
}

.diff-盘盈 {
  border-left: 4px solid #67c23a;
}

.diff-状态不符 {
  border-left: 4px solid #e6a23c;
}

.diff-位置不符 {
  border-left: 4px solid #409eff;
}

/* 处理对话框样式 */
.asset-info-display {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
</style>